package com.auth;

import lombok.extern.slf4j.Slf4j;
import org.springframework.expression.*;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

@Slf4j
public class Spel {

    private static final SpelExpressionParser expressionParser = new SpelExpressionParser();

    public static Object getValueByExpression(Object model, String exp) {

        try {

            EvaluationContext evaluationContext = new StandardEvaluationContext();

            evaluationContext.setVariable("model", model);

            Expression expression = expressionParser.parseExpression(exp, new TemplateParserContext());

            return expression.getValue(evaluationContext, Object.class);

        } catch (ParseException e) {

            log.warn("ParseException analysis the parameter is {}", model);

        } catch (EvaluationException e) {

            log.warn("EvaluationException analysis the parameter is {}", model);

        }

        return null;

    }

}
